<?php
namespace app\common\logic;

use app\common\exception\FailException;
use app\common\model\RealBonusMember;
use fast\Random;
use think\Controller;
use think\Db;
use think\Exception;
use weixin_pay\WxRedpack;

class Withdraw extends Controller
{
    //1.会员提现(满额度提现)，2.股东提现（随时可提），3.代理金提现（随时可提）4.红包提现（随时可提）5.商家提现 （随时可提）6.内部提现 （随时可提）7.一级代理提现 （随时可提)
    public function userwithdraw($uid,$money,$pay_password,$put_type,$card_id=0,$txtype=1,$usertype=1){
     
        if($usertype==1){
            $userdata=\app\common\model\User::where("id",$uid)->where("status",1)->find();
        }elseif($usertype==5){
            $userdata=RealBonusMember::where("id",$uid)->where("status",1)->find();

        }elseif($usertype==2){
            $userdata=\app\common\model\Shop::where("id",$uid)->where("status",1)->find();

        }elseif($usertype==3){
            $userdata=\app\common\model\Agent::where("id",$uid)->where("status",1)->find();

        }

        $put_service_bl=Db::table("t_config")->where("name","put_service")->value("data");//手续费
        $put_times=Db::table("t_config")->where("name","put_times")->value("data");//今日提现次数
        $min_put_money=Db::table("t_config")->where("name","min_put_money")->value("data");//最小提现额度
        $max_put_money=Db::table("t_config")->where("name","max_put_money")->value("data");//最大提现额度
        if($usertype==1){
            if(!$userdata['pay_password']){

                throw new FailException(["code"=>201,"msg"=>"支付密码未设置","errorCode"=>432]);
            }
            if($userdata['pay_password']!=md5($pay_password)){
                throw new FailException(["code"=>201,"msg"=>"支付密码错误","errorCode"=>404]);
            }
        }
        $money=abs($money);
        $service_moeny=floor($put_service_bl*$money*100)/100;  //服务费
        $real_money=$money-$service_moeny;   //最后到账费用
        if($min_put_money>$money){
            throw new FailException(["code"=>201,"msg"=>"最小提现额度为".$min_put_money."元，请满足最小提现额度","errorCode"=>404]);
        }
        if($put_type==2){

            if($max_put_money<$money){
                throw new FailException(["code"=>201,"msg"=>"最大提现额度为".$max_put_money."元，请不要超过最大提现额度","errorCode"=>404]);
            }
            if(!$userdata['openid']){
                throw new FailException(["code"=>201,"msg"=>"请先绑定微信再进行微信提现","errorCode"=>533]);
            }
        }
        if($put_type==3){
            if(!$card_id){

                throw new FailException(["code"=>201,"msg"=>"请选择银行卡号","errorCode"=>404]);
            }

            $cardinfo= Db::table("t_card")->where("uid",$uid)->where("usertype",$usertype)->where("id",$card_id)->find();

            if(!$cardinfo){
                throw new FailException(["code"=>201,"msg"=>"卡号不存在","errorCode"=>404]);
            }
        }

        if($usertype!=2){
            if($put_times!=-1){
                $starttime=date("Y-m-d",time());
                $endtime=date("Y-m-d",time())." 23:59:59";
                $count=Db::table("t_withdraw")->where("addtime","between",[strtotime($starttime),strtotime($endtime)])->where("type",$txtype)->where("usertype",$usertype)->where("uid",$uid)->count();
                if($count>$put_times){
                    throw new FailException(["code"=>201,"msg"=>"今日提现次数已经用完","errorCode"=>404]);
                }
            }

        }else{
            if($put_times!=-1){
                $starttime=date("Y-m-d",time());
                $endtime=date("Y-m-d",time())." 23:59:59";
                $count=Db::table("t_shop_capital_put")->where("created_at","between",[$starttime,$endtime])->where("shop_id",$uid)->count();
                if($count>$put_times){
                    throw new FailException(["code"=>201,"msg"=>"今日提现次数已经用完","errorCode"=>404]);
                }
            }

        }


        if($usertype==1&&$txtype==1) {    //会员收益提现
            Db::startTrans();
            try {

                $capitaldata = Db::table("t_capital")->where("type",2)->where("uid", $uid)->where("status", 1)->lock(true)->find();
                $user_role_data=Db::table("t_user_role")->where("id",$userdata["role_id"])->find();

                if ($capitaldata['consumer'] < $user_role_data['max_pay']) {
                    Db::rollback();
                    throw new FailException(["code" => 201, "msg" => "未达到提现条件,请先达到消费".$user_role_data['max_pay']."元", "errorCode" => 404]);
                }

                if ($capitaldata['put_out_money'] < $money) {
                    Db::rollback();
                    throw new FailException(["code" => 201, "msg" => "可提现余额不足", "errorCode" => 404]);
                }


                $sy_money = $capitaldata['put_out_money'] - $money; //剩余提现金额

                Db::table("t_capital")->where("type",2)->where("uid", $uid)->where("status", 1)->update([
                    "put_out_money" => $sy_money
                ]);
                $put_num = Random::numeric(26);
                if ($put_type == 3) {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "cid" => $capitaldata['id'],
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "card" => $cardinfo['card'],
                        "bankname" => $cardinfo['bankname'],
                        "name" => $cardinfo['name'],
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money

                    ];

                } else {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "cid" => $capitaldata['id'],
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money

                    ];
                }

                $wid = Db::table("t_withdraw")->insertGetId($insertdata_withdraw);

                $insertdata_withdraw['id'] = $wid;

                Db::table("t_capital_water")->insert([
                    "uid" => $uid,
                    "type" => 5,
                    "cid" => $capitaldata['id'],
                    "name" => "用户" . $userdata['username'] . "提现" . $money . "元",
                    "money" => 0 - $money,
                    "addtime" => time(),
                    "put_id" => $wid
                ]);

                if ($put_type == 2) {
                    $this->wx_withdraw($userdata['openid'], $real_money, $put_num, "微信提现",1);
                }

                Db::commit();
            } catch (FailException $e) {
                Db::rollback();
                throw new FailException(["code" => 201, "msg" => $e->msg, "errorCode" => 404]);
            }
        }elseif($usertype==1&&$txtype==4){   //红包提现

            Db::startTrans();
            try {

                $capitaldata = Db::table("t_capital")->where("type",2)->where("uid", $uid)->where("status", 1)->lock(true)->find();

                if ($capitaldata['packet_money'] < $money) {
                    Db::rollback();
                    throw new FailException(["code" => 201, "msg" => "红包余额不足", "errorCode" => 404]);
                }


                $sy_packet_money = $capitaldata['packet_money'] - $money; //剩余提现金额

                Db::table("t_capital")->where("type",2)->where("uid", $uid)->where("status", 1)->update([
                    "packet_money" => $sy_packet_money
                ]);
                $put_num = Random::numeric(26);
                if ($put_type == 3) {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "cid" => $capitaldata['id'],
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "card" => $cardinfo['card'],
                        "bankname" => $cardinfo['bankname'],
                        "name" => $cardinfo['name'],
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money
                    ];

                } else {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "cid" => $capitaldata['id'],
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money

                    ];
                }

                $wid = Db::table("t_withdraw")->insertGetId($insertdata_withdraw);

                $insertdata_withdraw['id'] = $wid;

                Db::table("t_capital_water")->insert([
                    "uid" => $uid,
                    "type" => 12,
                    "cid" => $capitaldata['id'],
                    "name" => "用户" . $userdata['username'] . "红包提现" . $money . "元",
                    "money" => 0 - $money,
                    "addtime" => time(),
                    "put_id" => $wid
                ]);

                if ($put_type == 2) {
                    $this->wx_withdraw($userdata['openid'], $real_money, $put_num, "微信提现",1);
                }

                Db::commit();
            } catch (FailException $e) {
                Db::rollback();
                throw new FailException(["code" => 201, "msg" =>$e->msg, "errorCode" => 404]);
            }




        }elseif($usertype==1&&$txtype==2){  //股东提现

            Db::startTrans();
            try {

                $capitaldata = Db::table("t_capital")->where("type",2)->where("uid", $uid)->where("status", 1)->lock(true)->find();

                if ($capitaldata['bonus_money'] < $money) {
                    Db::rollback();
                    throw new FailException(["code" => 201, "msg" => "股东分红余额不足", "errorCode" => 404]);
                }


                $sy_bonus_money = $capitaldata['bonus_money'] - $money; //剩余提现金额

                Db::table("t_capital")->where("type",2)->where("uid", $uid)->where("status", 1)->update([
                    "bonus_money" => $sy_bonus_money
                ]);
                $put_num = Random::numeric(26);
                if ($put_type == 3) {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "cid" => $capitaldata['id'],
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "card" => $cardinfo['card'],
                        "bankname" => $cardinfo['bankname'],
                        "name" => $cardinfo['name'],
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money
                    ];

                } else {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "cid" => $capitaldata['id'],
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money

                    ];
                }

                $wid = Db::table("t_withdraw")->insertGetId($insertdata_withdraw);

                $insertdata_withdraw['id'] = $wid;

                Db::table("t_capital_water")->insert([
                    "uid" => $uid,
                    "type" => 13,
                    "cid" => $capitaldata['id'],
                    "name" => "用户" . $userdata['username'] . "红包提现" . $money . "元",
                    "money" => 0 - $money,
                    "addtime" => time(),
                    "put_id" => $wid
                ]);

                if ($put_type == 2) {
                    $this->wx_withdraw($userdata['openid'], $real_money, $put_num, "微信提现",1);
                }

                Db::commit();
            } catch (FailException $e) {
                Db::rollback();
                throw new FailException(["code" => 201, "msg" =>$e->msg, "errorCode" => 404]);
            }




        }elseif($usertype==1&&$txtype==3){  //代理金提现

            Db::startTrans();
            try {

                $capitaldata = Db::table("t_capital")->where("type",2)->where("uid", $uid)->where("status", 1)->lock(true)->find();

                if ($capitaldata['agent_money'] < $money) {
                    Db::rollback();
                    throw new FailException(["code" => 201, "msg" => "代理金余额不足", "errorCode" => 404]);
                }


                $sy_agent_money = $capitaldata['agent_money'] - $money; //剩余提现金额

                Db::table("t_capital")->where("type",2)->where("uid", $uid)->where("status", 1)->update([
                    "agent_money" => $sy_agent_money
                ]);
                $put_num = Random::numeric(26);
                if ($put_type == 3) {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "cid" => $capitaldata['id'],
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "card" => $cardinfo['card'],
                        "bankname" => $cardinfo['bankname'],
                        "name" => $cardinfo['name'],
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money

                    ];

                } else {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "cid" => $capitaldata['id'],
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money

                    ];
                }

                $wid = Db::table("t_withdraw")->insertGetId($insertdata_withdraw);

                $insertdata_withdraw['id'] = $wid;

                Db::table("t_capital_water")->insert([
                    "uid" => $uid,
                    "type" => 14,
                    "cid" => $capitaldata['id'],
                    "name" => "用户" . $userdata['username'] . "代理金提现" . $money . "元",
                    "money" => 0 - $money,
                    "addtime" => time(),
                    "put_id" => $wid
                ]);

                if ($put_type == 2) {
                    $this->wx_withdraw($userdata['openid'], $real_money, $put_num, "微信提现",1);
                }

                Db::commit();
            } catch (FailException $e) {
                Db::rollback();
                throw new FailException(["code" => 201, "msg" =>$e->msg, "errorCode" => 404]);
            }




        }elseif($usertype==2&&$txtype==5){  //商家提现

            Db::startTrans();
            try {

                $capitaldata = Db::table("t_capital")->where("type",1)->where("uid", $uid)->where("status", 1)->lock(true)->find();

                if ($capitaldata['put_out_money'] < $money) {
                    Db::rollback();
                    throw new FailException(["code" => 201, "msg" => "余额不足", "errorCode" => 404]);
                }


                $sy_money = $capitaldata['put_out_money'] - $money; //剩余提现金额

                Db::table("t_capital")->where("type",1)->where("uid", $uid)->where("status", 1)->update([
                    "put_out_money" => $sy_money
                ]);
                $put_num = Random::numeric(26);
                if ($put_type == 3) {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "shop_id" => $uid,
                        "put_type"=>$put_type,
                        "cid" => $capitaldata['id'],
                        "put_type" => $put_type,
                        "created_at" => date("Y-m-d H:i:s",time()),
                        "money" => $money,
                        "real_money"=>$real_money,
                        "service_charge"=>$service_moeny,   //TODO 这里需要添加服务费
                        "card" => $cardinfo['card'],
                        "bankname" => $cardinfo['bankname'],
                        "name" => $cardinfo['name'],

                    ];

                } else {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "shop_id" => $uid,
                        "cid" => $capitaldata['id'],
                        "put_type" => $put_type,
                        "created_at" => date("Y-m-d H:i:s",time()),
                        "money" => $real_money,
                        "real_money"=>$money,
                        "service_charge"=>$service_moeny,   //TODO 这里需要添加服务费

                    ];
                }

                $wid = Db::table("t_shop_capital_put")->insertGetId($insertdata_withdraw);

                $insertdata_withdraw['id'] = $wid;

                if ($put_type == 2) {
                    $this->wx_withdraw($userdata['openid'], $real_money, $put_num, "微信提现",2);
                }

                Db::commit();
            } catch (FailException $e) {
                Db::rollback();
                throw new FailException(["code" => 201, "msg" =>$e->msg, "errorCode" => 404]);
            }




        }elseif($usertype==5&&$txtype==6){  //内部员工提现

            Db::startTrans();
            try {

                $capitaldata = Db::table("t_real_bonus_member")->where("id", $uid)->where("status", 1)->lock(true)->find();

                if ($capitaldata['money'] < $money) {
                    Db::rollback();
                    throw new FailException(["code" => 201, "msg" => "余额不足", "errorCode" => 404]);
                }


                $sy_money = $capitaldata['money'] - $money; //剩余提现金额

                Db::table("t_real_bonus_member")->where("id", $uid)->where("status", 1)->update([
                    "money" => $sy_money
                ]);
                $put_num = Random::numeric(26);
                if ($put_type == 3) {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money,
                        "card" => $cardinfo['card'],
                        "bankname" => $cardinfo['bankname'],
                        "name" => $cardinfo['name'],

                    ];

                } else {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money

                    ];
                }

                $wid = Db::table("t_withdraw")->insertGetId($insertdata_withdraw);

                $insertdata_withdraw['id'] = $wid;

                if ($put_type == 2) {
                    $this->wx_withdraw($userdata['openid'], $real_money, $put_num, "微信提现",1);
                }

                Db::commit();
            } catch (FailException $e) {
                Db::rollback();
                throw new FailException(["code" => 201, "msg" =>$e->msg, "errorCode" => 404]);
            }




        }elseif($usertype==3&&$txtype==7){  //代理商提现

            Db::startTrans();
            try {

                $capitaldata = Db::table("t_agent")->where("id", $uid)->where("status", 1)->lock(true)->find();

                if ($capitaldata['money'] < $money) {
                    Db::rollback();
                    throw new FailException(["code" => 201, "msg" => "余额不足", "errorCode" => 404]);
                }


                $sy_money = $capitaldata['money'] - $money; //剩余提现金额

                Db::table("t_agent")->where("id", $uid)->where("status", 1)->update([
                    "money" => $sy_money
                ]);
                $put_num = Random::numeric(26);
                if ($put_type == 3) {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money,
                        "card" => $cardinfo['card'],
                        "bankname" => $cardinfo['bankname'],
                        "name" => $cardinfo['name'],

                    ];

                } else {
                    $insertdata_withdraw = [
                        "put_num" => $put_num,
                        "uid" => $uid,
                        "put_type" => $put_type,
                        "addtime" => time(),
                        "money" => $money,
                        "usertype"=>$usertype,
                        "type"=>$txtype,
                        "service_charge"=>$service_moeny,
                        "real_money"=>$real_money

                    ];
                }

                $wid = Db::table("t_withdraw")->insertGetId($insertdata_withdraw);

                $insertdata_withdraw['id'] = $wid;

                if ($put_type == 2) {
                    $this->wx_withdraw($userdata['openid'], $real_money, $put_num, "微信提现",1);
                }

                Db::commit();
            } catch (FailException $e) {
                Db::rollback();
                throw new FailException(["code" => 201, "msg" =>$e->msg, "errorCode" => 404]);
            }




        }

        return  $insertdata_withdraw;

    }

    public function userwithdraw_dt($id,$userid,$type){
        if($type!=2) {
            return \app\common\model\Withdraw::where("uid",$userid)->where("id",$id)->where("usertype",$type)->find();
        }else{
            $data=Db::table("t_shop_capital_put")->where("id",$id)->where("shop_id",$userid)->find();

            $data['addtime']=strtotime($data['created_at']);
            $data['type']=5;
            $data['updatetime']=strtotime($data['updated_at']);
          
          return $data;
        }
         


    }


    public function userwithdraw_list($type,$txtype,$uid,$put_type=0,$status=0,$page=1,$num=20){

        $where=[];

        if($put_type){
            $where['put_type']=["eq",$put_type];
        }
        if($status){
            $where['status']=["eq",$status];
        }
        if($type!=2) {
            if ($txtype) {
                $where['type'] = ["eq", $txtype];
            }
            $where['usertype']=["eq",$type];
        }


        if($type==2){

            $data[0]=Db::table("t_shop_capital_put")->where("shop_id",$uid)->where($where)->page($page,$num)->order("created_at desc")->select();



            foreach ($data[0] as $k=>$va){
                $data[0][$k]['addtime']=strtotime($data[0][$k]['created_at']);
                $data[0][$k]['type']=5;
            }


            $data[1]=Db::table("t_shop_capital_put")->where("shop_id",$uid)->where("status",2)->sum("money");

        }else{

            $data[0]=  \app\common\model\Withdraw::where("uid",$uid)->where($where)->page($page,$num)->order("addtime desc")->select();


            $data[1]=  \app\common\model\Withdraw::where("uid",$uid)->where("status",2)->sum("money");
        }
        return $data;


    }

    public function wx_withdraw($openid,$money,$trade_no,$act_name,$type=1){
        $config = array(
            'wxappid'		=> 'wx73a49305e315e461',
            'mch_id'	 	=> '1449213202',
            'pay_apikey' 	=> 'tzld2018tzld2018tzld2018tzld2018',
            'api_cert'		=> getcwd().'/cer/apiclient_cert.pem',
            'api_key'		=> getcwd().'/cer/apiclient_key.pem'
        );

        $redpack = new WxRedpack($config);								//初始化类(同时传递参数)
//        $redpack->sendredpack($openid,$money,$trade_no,$act_name);		//发红包
        $res=$redpack->mchpay($openid,$money,$trade_no,$act_name);			//企业付款
        if($res['return_code']=='SUCCESS'){
            if($type==1) {
                Db::table("t_withdraw")->where("put_num", $trade_no)->update([
                    "status" => 2,
                    "updatetime"=>time()
                ]);
            }elseif($type==2){
                Db::table("t_shop_capital_put")->where("put_num", $trade_no)->update([
                    "status" => 2
                ]);
            }
        }
    }
}